package k8sutil

import (
	"flag"
	v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/klog/v2"
	"path/filepath"
	"time"

	"context"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

func GetNode() {
	clientset, err := createClient()
	if err != nil {
		klog.Error(err)
		return
	}
	opts := v1.ListOptions{
		Limit: 100,
	}
	ctx := getCtx()
	nodes, err := clientset.CoreV1().Nodes().List(ctx, opts)
	if err != nil {
		klog.Error(err)
		return
	}
	for _, v := range nodes.Items {
		klog.Info(v.Name)
	}
}

func GetPod() {
	clientset, err := createClient()
	if err != nil {
		klog.Error(err)
		return
	}
	opts := v1.ListOptions{
		Limit: 100,
	}
	ctx := getCtx()
	podwatch, err := clientset.CoreV1().Pods("kube-system").Watch(ctx, opts)
	if err != nil {
		klog.Error(err)
		return
	}
	for {
		select {
		case e, ok := <-podwatch.ResultChan():
			if !ok {
				// 说明该通道已经被close掉了
				klog.Warning("!!!!!podWatch chan has been close!!!!")
				klog.Info("clean chan over!")
				time.Sleep(time.Second * 5)
			}
			if e.Object != nil {
				klog.Info("chan is ok")
				klog.Info(e.Type)
				klog.Info(e.Object.DeepCopyObject())
			}
		}
	}
}
func GetDeployment(ns string) {
	clientset, err := createClient()
	if err != nil {
		klog.Error(err)
		return
	}
	opts := v1.ListOptions{
		Watch: false,
	}
	ctx := getCtx()
	dp, err := clientset.AppsV1().Deployments(ns).List(ctx, opts)
	for _, v := range dp.Items {
		klog.Info(v.Name, v.Status, v.APIVersion)
	}
}

func homeDir() string {
	/*h := os.Getenv("HOME")
	if  h == "" {
		h = os.Getenv("USERPROFILE") // windows
	}*/
	h := "/root"

	klog.Info("home:{},%s", h)
	return h

}
func createClient() (clientset *kubernetes.Clientset, err error) {
	var kubeconfig *string
	if home := homeDir(); home != "" {
		kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
	}
	config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
	if err != nil {
		panic(err.Error())
	}

	// create the clientset
	clientset, err = kubernetes.NewForConfig(config)
	return
}
func GetNamespace() {
	clientset, err := createClient()
	if err != nil {
		klog.Error(err)
		return
	}
	opts := v1.ListOptions{
		Watch: false,
	}
	ctx := getCtx()
	ns, err := clientset.CoreV1().Namespaces().List(ctx, opts)
	for _, v := range ns.Items {
		klog.Info(v.Name)
	}
}
func GetCs() {
	clientset, err := createClient()
	if err != nil {
		klog.Error(err)
		return
	}
	opts := v1.ListOptions{
		Watch: false,
	}
	ctx := getCtx()
	ns, err := clientset.CoreV1().ComponentStatuses().List(ctx, opts)
	for _, v := range ns.Items {
		klog.Infof(v.Name, v.String())
	}
}

func getCtx() context.Context {
	ctx := context.Background()
	//defer cancel() // 当我们完成消耗整数时取消
	return ctx
}

func GetResource() {
	GetNamespace()
	GetNode()
	GetPod()
	GetCs()
}
